package com.tiza.xiaoyoubao.ui.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.tianze.library.base.BaseFragment;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.Constants;
import com.tiza.xiaoyoubao.app.UIHelper;
import com.tiza.xiaoyoubao.entity.DnTBTaskOrderInfo;
import com.tiza.xiaoyoubao.entity.InsertTaskInfo;
import com.tiza.xiaoyoubao.entity.TaoBaoAccountInfo;
import com.tiza.xiaoyoubao.entity.TaskOrderInfo;
import com.tiza.xiaoyoubao.entity.UserInfo;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;
import com.tiza.xiaoyoubao.utils.DateUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

import static com.tiza.xiaoyoubao.R.id.tv_orderNum;
import static com.tiza.xiaoyoubao.R.id.tv_userId;

/**
 * Created by mapple on 17/4/11.
 * 电脑淘宝任务
 */

public class DNTaoBaoTaskDetialFragment extends BaseFragment {
    @BindView(R.id.lv_listView)
    ListView lv_listView;
    @BindView(R.id.tv_taskId)
    TextView tv_taskId;
    @BindView(R.id.tv_taskMoney)
    TextView tv_taskMoney;
    @BindView(R.id.tv_taskNum)
    TextView tv_taskNum;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.bt_type)
    Button bt_type;
    @BindView(R.id.tv_goodsType)
    TextView tv_goodsType;
    @BindView(R.id.tv_keyWord)
    TextView tv_keyWord;
    @BindView(R.id.tv_buyNumber)
    TextView tv_buyNumber;
    @BindView(R.id.tv_eva)
    TextView tv_eva;
    @BindView(R.id.tv_additionalRequest)
    TextView tv_additionalRequest;
    @BindView(R.id.view_bindingTaoBao)
    View view_bindingTaoBao;
    DateFormat df;
    Date date;
    long startTime, endTime;
    private List<TaoBaoAccountInfo> mList = new ArrayList<>();
    private List<TaoBaoAccountInfo> mList2 = new ArrayList<>();
    private TaoBaoInfoAdapter mTaoBaoInfoAdapter = new TaoBaoInfoAdapter();
    private DnTBTaskOrderInfo dnTBTaskOrderInfo;
    private String account;
    UserInfo userInfo = Hawk.get(Constants.KEY_USER_INFO, (UserInfo) null);
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dn_taobao_detial;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        dnTBTaskOrderInfo = (DnTBTaskOrderInfo) args.getSerializable("info");
        if (null == dnTBTaskOrderInfo) {
            toast("详情加载失败");
            finish();
        }
    }

    @Override
    protected void initData() {
        df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    @Override
    protected void initView() {
        getBankTaoBao();
        tv_taskId.setText("ID:" + dnTBTaskOrderInfo.getUserId());
        tv_money.setText(DateUtils.formateRate(dnTBTaskOrderInfo.getBaseCmi()));
        tv_taskMoney.setText(dnTBTaskOrderInfo.getPriceSection() + "元");
        tv_taskNum.setText("剩余" + dnTBTaskOrderInfo.getTaskNumber() + "单");
        tv_goodsType.setText(dnTBTaskOrderInfo.getSingleMulti());
        bt_type.setText(dnTBTaskOrderInfo.getBackName());
        if (TextUtils.isEmpty(dnTBTaskOrderInfo.getKeywords())) {
            tv_keyWord.setText("无");
        } else {
            tv_keyWord.setText(dnTBTaskOrderInfo.getKeywords());
        }
        tv_buyNumber.setText(dnTBTaskOrderInfo.getNumber());
        if (dnTBTaskOrderInfo.getRemarks().equals(" ")) {
            tv_additionalRequest.setText("此商家无其他要求");
        } else {
            tv_additionalRequest.setText(dnTBTaskOrderInfo.getRemarks());
        }
        lv_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                if (mList2.get(i).getNumber()==0) {
                    toast("今日可接单数已达上线");
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                    builder.setTitle("提示");
                    String message = "确认使用" + mList2.get(i)
                            .getAccount() + "接任务吗?\n接单2小时内必须完成任务操作,否则将扣除1金," +
                            "如果5分钟内取消不扣金";
                    builder.setMessage(message);
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                date = df.parse(df.format(new Date()));
                                startTime = date.getTime() / 1000;
                                endTime = startTime + 7200;
                                // endTime = startTime + 300;
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            account = mList2.get(i).getAccount();
                            insertTask();
                            // 隐藏当前对话框
                            dialog.dismiss();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 隐藏当前对话框
                            toast("取消");
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                }
            }

        });
    }

    @OnClick({R.id.view_bindingTaoBao})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_bindingTaoBao:
                UIHelper.showAccountBinding(mActivity);
                finish();
                break;
            default:
                break;
        }
    }

    private void insertTask() {
        ApiHttpClient.insertTask(this,
                String.valueOf(dnTBTaskOrderInfo.getId()), dnTBTaskOrderInfo.getTaskCode(),
                dnTBTaskOrderInfo.getUserId(), account,
                userInfo.getWebzzCmsBuyerInfo().getUserid(),
                String.valueOf(startTime), String.valueOf(endTime), "001",
                String.valueOf(dnTBTaskOrderInfo.getShopID()),
                new JsonCallback<InsertTaskInfo>(InsertTaskInfo.class) {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        toast("接单失败");
                    }

                    @Override
                    public void onResponse(ResponseInfo<InsertTaskInfo> response) {
                        int code = response.getCode();
                        String message = response.getMessage();
                        if (code == 1) {
                            showWarnDialog(message);
                            return;
                        }
                        List<InsertTaskInfo> data = response.getData();
                        if (null == data || data.size() == 0) {
                            toast("接单失败");
                            return;
                        }
                        InsertTaskInfo insertTaskInfo = data.get(0);
                        Hawk.put(Constants.KEY_INSERTTASK_INFO, insertTaskInfo);
                        UIHelper.showDnAttention(mActivity);
                        finish();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                    }
                }
        );
    }

    private void getBankTaoBao() {
        ApiHttpClient.getBuyerTaoBao(this, userInfo.getWebzzCmsBuyerInfo().getUserid(),
                new JsonCallback<TaoBaoAccountInfo>(TaoBaoAccountInfo.class) {
                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        toast("网络异常,请稍后重试");
                    }

                    @Override
                    public void onResponse(
                            ResponseInfo<TaoBaoAccountInfo> response
                    ) {
                        int code = response.getCode();
                        String message = response.getMessage();
                        if (code == 1) {
                            showWarnDialog(message);
                            return;
                        }
                        mList = response.getData();
                        if (null == mList || mList.size() == 0) {
                            view_bindingTaoBao.setVisibility(View.VISIBLE);
                        } else {
                            for (int i = 0; i < mList.size(); i++) {
                                if (mList.get(i).getAuth() == 1) {
                                    mList2.add(mList.get(i));
                                }
                            }
                        }
                        if (mList2.size() == 0) {
                            view_bindingTaoBao.setVisibility(View.VISIBLE);
                        } else {
                            lv_listView.setAdapter(mTaoBaoInfoAdapter);
                        }
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                    }
                }
        );
    }

    class TaoBaoInfoAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList2.size();
        }

        @Override
        public Object getItem(int position) {
            return mList2.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
          ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(getContext(), R.layout.item_taobao_info, null);
                holder = new ViewHolder();
                holder.tv_userId = (TextView) convertView.findViewById(tv_userId);
                holder.tv_orderNum = (TextView) convertView.findViewById(tv_orderNum);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tv_userId.setText(mList2.get(position).getAccount());
            holder.tv_orderNum.setText("(今日可接单" + mList2.get(position).getNumber() + "笔)");
            return convertView;
        }
    }

    static class ViewHolder {

        public TextView tv_userId;
        public TextView tv_orderNum;
    }
}
